package com.xoa.dev.pz.service;





import com.xoa.model.users.Users;
import com.xoa.dev.pz.dao.MenuJdtMapper;
import com.xoa.dev.pz.dao.PzCampusInfoMapper;
import com.xoa.dev.pz.model.PzCampusInfo;
import com.xoa.service.users.UsersService;
import com.xoa.dao.party.GridInfoMapper;
import com.xoa.model.party.GridInfo;
import com.xoa.util.ExcelUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.netdisk.CheckAll;
import com.xoa.util.page.PageParams;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by gsb on 2017/12/5.
 */
@Service
public class PzCampusInfoService {

    @Resource
    private PzCampusInfoMapper pzCampusInfoMapper;

    @Resource
    private UsersService usersService;
    @Resource
    private MenuJdtMapper menuJdtMapper;

    @Autowired
    GridInfoMapper gridInfoMapper;

    /**
     * 创建人：季佳伟
     * 创建时间：2017-12-05 下午18:26:17
     * 方法介绍：校园及周边信息添加
     * 参数说明：
     */
    public ToJson<PzCampusInfo> insertSelective(PzCampusInfo pzCampusInfo, HttpServletRequest request){
        ToJson<PzCampusInfo> json = new ToJson<>();
        try {
            Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
            String userId = user.getUserId();
            pzCampusInfo.setCreateUser(userId);
            SimpleDateFormat tempDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String datetime = tempDate.format(new Date());
            pzCampusInfo.setCreateTime(datetime);
            pzCampusInfoMapper.insertSelective(pzCampusInfo);
            json.setFlag(0);
            json.setMsg("true");

        }catch (Exception e){
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setFlag(1);
        }
        return json;
    }
    /**
     * 创建人：季佳伟
     * 创建时间：2017-12-05 下午18:26:17
     * 方法介绍：校园及周边信息修改
     * 参数说明：
     */
    public ToJson<PzCampusInfo> updateByPrimaryKeySelective(PzCampusInfo pzCampusInfo){
        ToJson<PzCampusInfo> json = new ToJson<>();
        try {
            pzCampusInfoMapper.updateByPrimaryKeySelective(pzCampusInfo);
            json.setFlag(0);
            json.setMsg("ok");
        }catch (Exception e){
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setFlag(1);
        }
        return json;

    }
    /**
     * 创建人：季佳伟
     * 创建时间：2017-12-05 下午18:26:17
     * 方法介绍：校园及周边信息删除
     * 参数说明：
     */
    public ToJson<PzCampusInfo> deleteByPrimaryKey(Integer sId) {
        ToJson<PzCampusInfo> json = new ToJson<>();
        try {
            pzCampusInfoMapper.deleteByPrimaryKey(sId);
            json.setFlag(0);
            json.setMsg("ok");
        }catch (Exception e){
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setFlag(1);
        }
        return json;
    }
    /**
     * 创建人：季佳伟
     * 创建时间：2017-12-05 下午18:26:17
     * 方法介绍：校园及周边信息详情
     * 参数说明：
     */
    public ToJson<PzCampusInfo> selectById(Integer sId) {
        ToJson<PzCampusInfo> json = new ToJson<>();
        try {
            PzCampusInfo pzCampusInfo = pzCampusInfoMapper.selectById(sId);
            if(!StringUtils.checkNull(pzCampusInfo.getGridUserId())){
                pzCampusInfo.setGridUserName(usersService.getUserNameById(pzCampusInfo.getGridUserId()));
            }
            json.setObject(pzCampusInfo);
            json.setFlag(0);
            json.setMsg("ok");

        }catch (Exception e){
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setFlag(1);
        }
        return json;

    }
    /**
     * 创建人：季佳伟
     * 创建时间：2017-12-05 下午18:26:17
     * 方法介绍：校园及周边信息列表
     * 参数说明：
     */
    public ToJson<PzCampusInfo> queryAll(PzCampusInfo pzCampusInfo, Integer page, Integer pageSize, boolean useFlag, HttpServletRequest request){
        ToJson<PzCampusInfo> json = new ToJson<>();
        PageParams pageParams=new PageParams();
        pageParams.setPage(page);
        pageParams.setPageSize(pageSize);
        pageParams.setUseFlag(useFlag);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("page", pageParams);
        Map<String, Object> param = new HashMap<String, Object>();
        Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
        param.put("userId", user.getUserId());
        param.put("userPriv", user.getUserPriv());
        param.put("deptId", user.getDeptId());
        String menuModel=menuJdtMapper.selMenuByModel("2");
        if(!CheckAll.checkAll(menuModel,param)){
            pzCampusInfo.setCreateUser(user.getUserId());
        }
        map.put("pzCampusInfo",pzCampusInfo);
        try {
            List<PzCampusInfo> pzCampusInfoList = pzCampusInfoMapper.queryAll(map);
            if(pzCampusInfoList != null){
                for (PzCampusInfo pzCampusInfo1 : pzCampusInfoList){
                    if(!StringUtils.checkNull(pzCampusInfo1.getGridUserId())){
                        pzCampusInfo1.setGridUserName(usersService.getUserNameById(pzCampusInfo1.getGridUserId()));

                    }

                }
            }
            json.setObj(pzCampusInfoList);
            json.setTotleNum(pageParams.getTotal());
            json.setFlag(0);
            json.setMsg("ok");
        }catch (Exception e){
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setFlag(1);
        }

        return json;

    }

    /**
     * 创建人：季佳伟
     * 创建时间：2017-12-06 下午14:26:17
     * 方法介绍：导入校园及周边信息
     * 参数说明：
     */
    public ToJson<PzCampusInfo> importCampusInfo(MultipartFile file, HttpServletRequest request, HttpServletResponse response){
        ToJson<PzCampusInfo> json = new ToJson<>();
        // 成功次数
        Integer successCount = 0;
        try {
            //判读当前系统
            //读取配置文件
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String osName = System.getProperty("os.name");
            StringBuffer path = new StringBuffer();
            if (osName.toLowerCase().startsWith("win")) {
                path = path.append(rb.getString("upload.win"));
            } else {
                path = path.append(rb.getString("upload.linux"));
            }
            // 判断是否为空文件
            if (file.isEmpty()) {
                json.setMsg("请上传文件！");
                json.setFlag(1);
                return json;
            } else {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) {
                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    int pos = fileName.indexOf(".");
                    String extName = fileName.substring(pos);
                    String newFileName = uuid + extName;
                    File dest = new File(path.toString(), newFileName);
//                    file.transferTo(dest);
                    // 将文件上传成功后进行读取文件
                    // 进行读取的路径
                    String readPath = path.append(System.getProperty("file.separator")).append(newFileName).toString();
//                    InputStream in = new FileInputStream(readPath);
                    InputStream in =  file.getInputStream();
                    HSSFWorkbook excelObj = new HSSFWorkbook(in);
                    HSSFSheet sheetObj = excelObj.getSheetAt(0);
                    Row row = sheetObj.getRow(0);
                    int colNum = row.getPhysicalNumberOfCells();
                    int lastRowNum = sheetObj.getLastRowNum();
                    List<PzCampusInfo> pzCampusInfoList = new ArrayList<PzCampusInfo>();
                    PzCampusInfo pzCampusInfo = null;
                    for (int i = 1; i <= lastRowNum; i++) {
                        pzCampusInfo = new PzCampusInfo();
                        Users user= SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users());
                        pzCampusInfo.setCreateUser(user.getUserId());
                        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        pzCampusInfo.setCreateTime(sd.format(new Date()));
                        row = sheetObj.getRow(i);
                        if (row != null) {
                            for (int j = 0; j < colNum; j++) {
                                Cell cell = row.getCell(j);
                                String value = "";
                                if (cell != null) {
                                    switch (j) {
                                        case 0:
                                            //所属网格
                                            String as = cell.getStringCellValue();
                                            GridInfo info = gridInfoMapper.selectByUGridName(as);

                                            pzCampusInfo.setGridId(info.getGridId());
                                            break;
                                        case 1:
                                            //学校名称
                                            pzCampusInfo.setSchoolName(cell.getStringCellValue());
                                            break;
                                        case 2:
                                            //学校类型
                                            pzCampusInfo.setSchoolType(cell.getStringCellValue());
                                            break;
                                        case 3:
                                            //学校地址
                                            pzCampusInfo.setSchoolAddress(cell.getStringCellValue());
                                            break;
                                        case 4:
                                            //学校性质
                                           pzCampusInfo.setSchoolNature(cell.getStringCellValue());
                                            break;
                                        case 5:
                                            //关注程度
                                            pzCampusInfo.setAttention(cell.getStringCellValue());
                                            break;
                                        case 6:
                                            //治保人数
//                                            BigDecimal big9=new BigDecimal(cell.getNumericCellValue());
//                                            value = big9.toString();
//                                            //解决1234.0  去掉后面的.0
//                                            if(null!=value&&!"".equals(value.trim())){
//                                                String[] item = value.split("[.]");
//                                                if(1<item.length&&"0".equals(item[1])){
//                                                    value=item[0];
//                                                }
//                                            }
                                            pzCampusInfo.setSecurityNum(Integer.parseInt(cell.getStringCellValue()));
                                            break;
                                        case 7:
                                            //主要负责人
                                            pzCampusInfo.setMainResPerson(cell.getStringCellValue());
                                            break;
                                        case 8:
                                            //主要负责人电话号
//                                            BigDecimal big11=new BigDecimal(cell.getNumericCellValue());
//                                            value = big11.toString();
//                                            //解决1234.0  去掉后面的.0
//                                            if(null!=value&&!"".equals(value.trim())){
//                                                String[] item = value.split("[.]");
//                                                if(1<item.length&&"0".equals(item[1])){
//                                                    value=item[0];
//                                                }
//                                            }
                                            pzCampusInfo.setMainPersonTel(cell.getStringCellValue());
                                            break;
                                        case 9:
                                            //主要负责人手机号
//                                            BigDecimal big12=new BigDecimal(cell.getNumericCellValue());
//                                            value = big12.toString();
//                                            //解决1234.0  去掉后面的.0
//                                            if(null!=value&&!"".equals(value.trim())){
//                                                String[] item = value.split("[.]");
//                                                if(1<item.length&&"0".equals(item[1])){
//                                                    value=item[0];
//                                                }
//                                            }
                                            cell.setCellType(CellType.STRING);
                                            pzCampusInfo.setMainPersonMobil(cell.getStringCellValue());
                                            break;
                                        case 10:
                                            //分管治保负责人
                                            pzCampusInfo.setSecurityResPerson(cell.getStringCellValue());
                                            break;
                                        case 11:
                                            //分管治保负责人电话号
//                                            BigDecimal big14=new BigDecimal(cell.getNumericCellValue());
//                                            value = big14.toString();
//                                            //解决1234.0  去掉后面的.0
//                                            if(null!=value&&!"".equals(value.trim())){
//                                                String[] item = value.split("[.]");
//                                                if(1<item.length&&"0".equals(item[1])){
//                                                    value=item[0];
//                                                }
//                                            }
                                            cell.setCellType(CellType.STRING);
                                            pzCampusInfo.setSecurityPersonTel(cell.getStringCellValue());
                                            break;
                                        case 12:
                                            //分管治保负责人手机号
//                                            BigDecimal big15=new BigDecimal(cell.getNumericCellValue());
//                                            value = big15.toString();
//                                            //解决1234.0  去掉后面的.0
//                                            if(null!=value&&!"".equals(value.trim())){
//                                                String[] item = value.split("[.]");
//                                                if(1<item.length&&"0".equals(item[1])){
//                                                    value=item[0];
//                                                }
//                                            }
                                            cell.setCellType(CellType.STRING);
                                            pzCampusInfo.setSecurityPersonMobil(cell.getStringCellValue());
                                            break;
                                        case 13:
                                            //在校学生人数
//                                            BigDecimal big16=new BigDecimal(cell.getNumericCellValue());
//                                            value = big16.toString();
//                                            //解决1234.0  去掉后面的.0
//                                            if(null!=value&&!"".equals(value.trim())){
//                                                String[] item = value.split("[.]");
//                                                if(1<item.length&&"0".equals(item[1])){
//                                                    value=item[0];
//                                                }
//                                            }
                                           // cell.setCellType(CellType.STRING);
                                            pzCampusInfo.setStudentNum(Integer.parseInt(cell.getStringCellValue()));
                                            break;
                                        case 14:
                                            //在校教师人数
//                                            BigDecimal big17=new BigDecimal(cell.getNumericCellValue());
//                                            value = big17.toString();
//                                            //解决1234.0  去掉后面的.0
//                                            if(null!=value&&!"".equals(value.trim())){
//                                                String[] item = value.split("[.]");
//                                                if(1<item.length&&"0".equals(item[1])){
//                                                    value=item[0];
//                                                }
//                                            }
                                            pzCampusInfo.setTeacherNum(Integer.parseInt(cell.getStringCellValue()));
                                            break;
                                        case 15:
                                            //保安人数
//                                            BigDecimal big18=new BigDecimal(cell.getNumericCellValue());
//                                            value = big18.toString();
//                                            //解决1234.0  去掉后面的.0
//                                            if(null!=value&&!"".equals(value.trim())){
//                                                String[] item = value.split("[.]");
//                                                if(1<item.length&&"0".equals(item[1])){
//                                                    value=item[0];
//                                                }
//                                            }
                                            pzCampusInfo.setSecurityGuardNum(Integer.parseInt(cell.getStringCellValue()));
                                            break;
                                        case 16:
                                            //治安岗亭数量
//                                            BigDecimal big19=new BigDecimal(cell.getNumericCellValue());
//                                            value = big19.toString();
//                                            //解决1234.0  去掉后面的.0
//                                            if(null!=value&&!"".equals(value.trim())){
//                                                String[] item = value.split("[.]");
//                                                if(1<item.length&&"0".equals(item[1])){
//                                                    value=item[0];
//                                                }
//                                            }
                                            cell.setCellType(CellType.STRING);
                                            if(cell.getStringCellValue()!=null){
                                                pzCampusInfo.setSecurityPostNum(Integer.parseInt(cell.getStringCellValue()));
                                            }
                                            break;
                                        case 17:
                                            //备注
                                            pzCampusInfo.setRemark(cell.getStringCellValue());
                                            break;




                                    }
                                }
                            }
                            int count = pzCampusInfoMapper.insertSelective(pzCampusInfo);
                            if(count>0) {
                                successCount = successCount + count;
                            }
                        }
                    }
                }
            }
            if(successCount>0){
                json.setMsg("ok");
                json.setTotleNum(successCount);
                json.setFlag(0);
                return  json;
            }
        }catch (Exception e){
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setFlag(1);
        }
        return json;
    }

    /**
     * 创建人：季佳伟
     * 创建时间：2017-12-06 下午16:12:17
     * 方法介绍：导出校园及周边信息
     * 参数说明：
     */
    public ToJson<PzCampusInfo> getCampusInfoExport(HttpServletRequest request, HttpServletResponse response,
                                                    PzCampusInfo pzCampusInfo, String export){

        ToJson<PzCampusInfo> json = new ToJson<>();
        try {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("pzCampusInfo",pzCampusInfo);
            List<PzCampusInfo> pzCampusInfoList = pzCampusInfoMapper.queryAll(map);
            if("0".equals(export)){
                json.setObj(pzCampusInfoList);
                json.setFlag(0);
                json.setMsg("ok");
            }else if ("1".equals(export)){
                HSSFWorkbook workbook1 = ExcelUtil.makeExcelHead("校园及周边信息导出",9);
                String[] secondTitles = { "所属网格",  "学校名称", "学校类型", "学校地址", "学校性质", "关注程度"
                        , "治保人数", "主要负责人", "主要负责人手机号",
                          "在校学生人数", "在校教师人数", "保安人数","创建人","创建时间","备注1","备注2","备注3"};
                HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbook1, secondTitles);
                String[] beanProperty = { "gridName",  "schoolName", "schoolType"
                        , "schoolAddress", "schoolNature", "attention", "securityNum", "mainResPerson"
                        , "mainPersonMobil",
                        "studentNum", "teacherNum", "securityGuardNum"
                        ,"createName","createTime", "remark","str1","str2"
                };
                HSSFWorkbook workbook = null;
                workbook = ExcelUtil.exportExcelData(workbook2, pzCampusInfoList, beanProperty);
                OutputStream out = response.getOutputStream();
                String filename = "校园及周边信息表.xls";
                filename = FileUtils.encodeDownloadFilename(filename, request.getHeader("user-agent"));
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                response.setHeader("content-disposition", "attachment;filename=" + filename);
                workbook.write(out);
                out.close();

            }
        }catch (Exception e){
            e.printStackTrace();
            json.setMsg(e.getMessage());
            json.setFlag(1);
        }
        return json;

    }
    }
